import {
  base64_encode,
  base64_decode
} from '../../../common/utils/base64';
import md5 from '../../../common/utils/md5';
import ws_util from '../../../common/utils/util';

const util = {};

util.checkauth = function(url, fn) {
  const path = url;
  util.request({
    url: 'entry/wxapp/user.check_inid',
    data: {
      path,
    },
    showLoading: true,
    success: (res) => {
      if (typeof fn === 'function') {
        fn();
      }
    },
  });
};

util.base64Encode = function(str) {
  return base64_encode(str);
};

util.base64Decode = function(str) {
  return base64_decode(str);
};

util.md5 = function(str) {
  return md5(str);
};

/**
	构造地址,
	@params action 格式为 'wxapp/home/navs'
	@params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
*/
util.url = function(action, querystring) {
  const app = getApp();
  let url = `${app.siteInfo.siteroot
  }?i=${app.siteInfo.uniacid
  }&t=${app.siteInfo.multiid
  }&v=${app.siteInfo.version
  }&divisionid=${app.siteInfo.divisionid
  }&from=wxapp&`;
      if (wx.systemInfo.environment === 'wxwork') {
    url += 'env=wxwork&';
      }else{
    url += 'env=wxapp&';
      }
  if (app.siteInfo.cfgtime) {
    url += `cfgtime=${app.siteInfo.cfgtime}&`;
  }
  if (action) {
    action = action.split('/');
    if (action[0]) {
      url += `c=${action[0]}&`;
    }
    if (action[1]) {
      url += `a=${action[1]}&`;
    }
    if (action[2]) {
      url += `do=${action[2]}&`;
    }
  }
  const sessionid = wx.getStorageSync('userInfo').sessionid;
  const state = getUrlParam(url, 'state');
  if (!state && sessionid) {
    url = `${url}state=v8uuid-${sessionid}&`;
  }

  if (querystring && typeof querystring === 'object') {
    for (const param in querystring) {
      if (param && querystring.hasOwnProperty(param) && querystring[param]) {
        url += `${param}=${querystring[param]}&`;
      }
    }
  }
  return url;
};

function getQuery(url) {
  const theRequest = [];
  if (url.indexOf('?') != -1) {
    const str = url.split('?')[1];
    const strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      if (strs[i].split('=')[0] && unescape(strs[i].split('=')[1])) {
        theRequest[i] = {
          name: strs[i].split('=')[0],
          value: unescape(strs[i].split('=')[1]),
        };
      }
    }
  }
  return theRequest;
}
/*
 * 获取链接某个参数
 * url 链接地址
 * name 参数名称
 */
function getUrlParam(url, name) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`); // 构造一个含有目标参数的正则表达式对象
  const r = url.split('?')[1].match(reg); // 匹配目标参数
  if (r != null) return unescape(r[2]);
  return null; // 返回参数值
}
/**
 * 获取签名 将链接地址的所有参数按字母排序后拼接加上token进行md5
 * url 链接地址
 * date 参数{参数名1 : 值1, 参数名2 : 值2} *
 * token 签名token 非必须
 */
function getSign(url, data, token) {
  const _ = require('../../../common/utils/underscore.js');
  // var md5 = require("../../../common/utils/md5.js");
  let querystring = '';
  let sign = getUrlParam(url, 'sign');
  if (sign || (data && data.sign)) {
    return false;
  }
  if (url) {
    querystring = getQuery(url);
  }
  if (data) {
    let theRequest = [];
    for (const param in data) {
      if (param && data[param]) {
        theRequest = theRequest.concat({
          name: param,
          value: data[param],
        });
      }
    }
    querystring = querystring.concat(theRequest);
  }
  // 排序
  querystring = _.sortBy(querystring, 'name');
  // 去重
  querystring = _.uniq(querystring, true, 'name');
  let urlData = '';
  for (let i = 0; i < querystring.length; i++) {
    if (querystring[i] && querystring[i].name && querystring[i].value) {
      urlData += `${querystring[i].name}=${querystring[i].value}`;
      if (i < (querystring.length - 1)) {
        urlData += '&';
      }
    }
  }
  token = token || getApp().siteInfo.token;
  sign = md5(urlData + token);
  return sign;
}
util.getSign = function(url, data, token) {
  return getSign(url, data, token);
};
/**
	二次封装微信wx.request函数、增加交互体全、配置缓存、以及配合直营店格式化返回数据

	@params option 弹出参数表，
	{
		url : 同微信,
		data : 同微信,
		header : 同微信,
		method : 同微信,
		success : 同微信,
		fail : 同微信,
		complete : 同微信,
		cachetime : 缓存周期，在此周期内不重复请求http，默认不缓存
	}
*/
util.request = function(option) {
  const _ = require('../../../common/utils/underscore.js');
  // var md5 = require("../../../common/utils/md5.js");
  // var app = getApp();
  var option = option || {};
  option.cachetime = option.cachetime ? option.cachetime : 0;
  option.showLoading = typeof option.showLoading === 'undefined' ? true : option.showLoading;

  // var openid = wx.getStorageSync("userInfo").openid;
  let url = option.url;
  if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
    url = util.url(url);
  }
  if (option.m) {
    url = `${url}m=${url.m}&`;
  } else {
    url += 'm=ws_party_const&';
  }
  const sign = getSign(url, option.data);
  if (sign) {
    url = `${url}sign=${sign}`;
  }
  if (!url) {
    return false;
  }
  // wx.showNavigationBarLoading();
  if (option.showLoading) {
    util.showLoading();
  }
  if (option.cachetime) {
    var cachekey = md5(url);
    const cachedata = wx.getStorageSync(cachekey);
    var timestamp = Date.parse(new Date());

    if (cachedata && cachedata.data) {
      if (cachedata.expire > timestamp) {
        if (option.complete && typeof option.complete === 'function') {
          option.complete(cachedata);
        }
        if (option.success && typeof option.success === 'function') {
          option.success(cachedata);
        }
        console.log(`cache:${url}`);
        wx.hideLoading();
        // wx.hideNavigationBarLoading();
        return true;
      }
      wx.removeStorageSync(cachekey);
    }
  }
  wx.request({
    url,
    data: option.data ? option.data : {},
    header: option.header ? option.header : {
      'content-type': 'application/x-www-form-urlencoded',
    },
    method: option.method ? option.method : 'POST',
    success(response) {
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      if (response.data.errno !== 0) {
        let pages = getCurrentPages();
        if (response.data.errno == '41009') {
          util.getUserInfo(() => {
            util.request(option);
          });
          return;
        } else if (response.data.errno === -100) {
          if (pages.length>0){
            let currentPage = pages[pages.length - 1];
            wx.setStorageSync('currentPage', currentPage);
          }
          wx.reLaunch({
            url: '/ws_party_const/pages/login/login',
          });
        } else if (response.data.errno == -99) {
          wx.showModal({
            title: '提示',
            content: '请先认证党员信息',
            showCancel: true,
            success: (res) => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/ws_party_const/pages/auth/index',
                });
              }else{
                if (pages.length > 1){
                  wx.navigateBack();
                }
              }
            },
          });
        } else if (option.fail && typeof option.fail === 'function') {
          option.fail(response.data);
        } else if (response.data.message) {
          if (response.data.data != null && response.data.data.redirect) {
            var redirect = response.data.data.redirect;
          } else {
            var redirect = '';
          }
          util.message(response.data.message, redirect, 'error');
        }
      } else {
        if (response.data.message) {
          util.message(response.data.message, '', 'success');
        }
        if (option.success && typeof option.success === 'function') {
          option.success(response.data);
        }
        // 写入缓存，减少HTTP请求，并且如果网络异常可以读取缓存数据
        if (option.cachetime) {
          const cachedata = {
            data: response.data,
            expire: timestamp + option.cachetime * 1000,
          };
          wx.setStorageSync(cachekey, cachedata);
        }
      }
    },
    fail(response) {
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      // 如果请求失败，尝试从缓存中读取数据
      // var md5 = require("../../../common/utils/md5.js");
      const cachekey = md5(url);
      const cachedata = wx.getStorageSync(cachekey);
      if (cachedata && cachedata.data) {
        if (option.success && typeof option.success === 'function') {
          option.success(cachedata);
        }
        console.log(`failreadcache:${url}`);
        return true;
      }
      util.message('网络请求超时', '', 'error');
    },
    complete(response) {
      if (option.complete && typeof option.complete === 'function') {
        option.complete(response.data);
      }
    },
  });
};

/**
 * 获取用户信息（兼容wq接口）
 */
util.getUserInfo = function(cb, wxInfo) {
  const login = function() {
    console.log('new start login');
    const userInfo = {
      sessionid: '',
      openid: '',
      wxInfo: '',
      memberInfo: '',
    };
    wx.login({
      success(res) {
        util.getUser((userInfo) => {
          if (wxInfo) {
            util.updateUser(wxInfo, (userInfo) => {
              typeof cb === 'function' && cb(userInfo);
            });
          } else {
            wx.getSetting({
              success: (res) => {
                if (res.authSetting['scope.userInfo'] || wx.canIUse('wx.getUserInfo')) {
                  wx.getUserInfo({
                    withCredentials: true,
                    success(wxInfo) {
                      util.updateUser(wxInfo, (userInfo) => {
                        typeof cb === 'function' && cb(userInfo);
                      });
                    },
                    fail() {
                      typeof cb === 'function' && cb(userInfo);
                    },
                  });
                } else {
                  typeof cb === 'function' && cb(userInfo);
                }
              },
            });
          }
        }, res.code);
      },
      fail() {
        wx.showModal({
          title: '获取信息失败',
          content: '请允许授权以便为您提供给服务',
          success(res) {
            if (res.confirm) {
              util.getUserInfo();
            }
          },
        });
      },
    });
  };
  // login();
  util.checkSession(login());
};
util.checkSession = function(cb){
  wx.checkSession({
    success(res) {
      // console.log('wx.checkSession==========', res);
      ws_util.request({
        url: 'auth/session/checkSession',
        data: {},
        cachetime: 0,
        showLoading: false,
        success(result) {
          // console.log("auth/session/checkSession========", result.data.data.check)
          if (!result.data.data.check) {
            typeof cb === 'function' && cb();
          }
        },
      });
    },
    fail() {
      // session_key 已经失效，需要重新执行登录流程
      typeof cb === 'function' && cb();
    },
  });
 
};
util.getUser = function(cb, code) {
  const userInfo = wx.getStorageSync('userInfo') || {};
  ws_util.request({
    url: 'auth/session/openid',
    data: {
      code: code || '',
    },
    cachetime: 0,
    showLoading: false,
    success(session) {
      // console.log('==========isopenqywx', session.data.data.isopenqywx);
      if (!session.data.errno) {
        userInfo.sessionid = session.data.data.sessionid;
        userInfo.openid = session.data.data.openid;
        wx.setStorageSync('userInfo', userInfo);
      }
      //企业微信
      if (session.data.data.isopenqywx) {
        util.qyCheckSession();
      }
      typeof cb === 'function' && cb(userInfo);
    },
  });
};

util.updateUser = function(wxInfo, cb) {
  const userInfo = wx.getStorageSync('userInfo');
  if (!wxInfo) {
    return typeof cb === 'function' && cb(userInfo);
  }
  userInfo.wxInfo = wxInfo.userInfo;
  ws_util.request({
    url: 'auth/session/userinfo',
    showLoading: false,
    data: {
      signature: wxInfo.signature,
      rawData: wxInfo.rawData,
      iv: wxInfo.iv,
      encryptedData: wxInfo.encryptedData,
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    cachetime: 0,
    success(res) {
      // console.log('==========1',res);
      if (res.data.errno == 0) {
        userInfo.memberInfo = res.data.data;
        wx.setStorageSync('userInfo', userInfo);
      }
      typeof cb === 'function' && cb(userInfo);
    },
  });
};

// 企业微信 
util.qyCheckSession = function(){
  // wx.getSystemInfo({
  //   success(result) {
      // console.log('=====environment=====', result.environment);
      // console.log('=====environment=====', wx.systemInfo.environment);
      if (wx.systemInfo.environment === 'wxwork') {
        wx.qy.checkSession({
          success(res) {
            // console.log('checkSession========',res);
            ws_util.request({
              url: 'auth/workwechat/checkSession',
              cachetime: 0,
              showLoading: false,
              success(session) {
                // console.log('auth/workwechat/checkSession===', session.data.data.check);
                if (!session.data.data.check){
                  util.qyLogin();
                }
              },
              fail() {
                // console.log('企业微信验证auth/workwechat/checkSession失败');
                util.qyLogin();
          },
        });
          },
          fail() {
            // console.log('企业微信验证checkSession失败');
            util.qyLogin();
      },
    });
      }
  //   }
  // })
};
//企业微信登录
util.qyLogin = function(){
  wx.qy.login({
    success(result) {
      if (result.code) {
        // 发起网络请求
        // console.log('企业微信login,code',result.code)
        ws_util.request({
          url: 'auth/workwechat/userid',
          data: {
            code: result.code,
          },
          cachetime: 0,
          showLoading: false,
          success(res) {
            // console.log('企业auth/workwechat/userid', res.data.data);
          },
        });
      } else {
        util.qyCheckSession();
        // console.log('企业微信login失败！', result)
      }
    },
  });
};
util.navigateBack = function(obj) {
  const delta = obj.delta ? obj.delta : 1;
  if (obj.data) {
    const pages = getCurrentPages();
    const curPage = pages[pages.length - (delta + 1)];
    if (curPage.pageForResult) {
      curPage.pageForResult(obj.data);
    } else {
      curPage.setData(obj.data);
    }
  }
  wx.navigateBack({
    delta, // 回退前 delta(默认为1) 页面
    success(res) {
      // success
      typeof obj.success === 'function' && obj.success(res);
    },
    fail(err) {
      // fail
      typeof obj.fail === 'function' && obj.fail(err);
    },
    complete() {
      // complete
      typeof obj.complete === 'function' && obj.complete();
    },
  });
};

/*
 * 提示信息
 * type 为 success, error 当为 success,  时，为toast方式，否则为模态框的方式
 * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称
 * navigate:/we7/pages/detail/detail 以 navigateTo 的方法跳转，
 * redirect:/we7/pages/detail/detail 以 redirectTo 的方式跳转，默认为 redirect
 */
util.message = function(title, redirect, type) {
  if (!title) {
    return true;
  }
  if (typeof title === 'object') {
    redirect = title.redirect;
    type = title.type;
    title = title.title;
  }
  if (redirect) {
    const redirectType = redirect.substring(0, 9);


    var url = '';


    var redirectFunction = '';
    if (redirectType == 'navigate:') {
      redirectFunction = 'navigateTo';
      url = redirect.substring(9);
    } else if (redirectType == 'redirect:') {
      redirectFunction = 'redirectTo';
      url = redirect.substring(9);
    } else {
      url = redirect;
      redirectFunction = 'redirectTo';
    }
  }
  if (!type) {
    type = 'success';
  }
  if (type == 'success') {
    wx.showToast({
      title,
      icon: 'success',
      duration: 1500,
      mask: !!url,
      complete() {
        if (url) {
          setTimeout(() => {
            wx[redirectFunction]({
              url,
            });
          }, 1800);
        }
      },
    });
  } else if (type == 'error') {
    if (url) {
      wx.showModal({
        title: '提示',
        content: title,
        complete() {
          if (url) {
            wx[redirectFunction]({
              url,
            });
          }
        },
      });
    } else {
      wx.showToast({
        icon: 'none',
        title,
        duration: 2000,
      });
    }
  }
};

util.user = util.getUserInfo;

// 封装微信等待提示，防止ajax过多时，show多次
util.showLoading = function() {
  const isShowLoading = wx.getStorageSync('isShowLoading');
  if (isShowLoading) {
    wx.hideLoading();
    wx.setStorageSync('isShowLoading', false);
  }
  wx.showLoading({
    title: '加载中',
    mask: true,
    complete() {
      wx.setStorageSync('isShowLoading', true);
    },
    fail() {
      wx.setStorageSync('isShowLoading', false);
    },
  });
};

util.showImage = function(event) {
  const url = event ? event.currentTarget.dataset.preview : '';
  if (!url) {
    return false;
  }
  wx.previewImage({
    urls: [url],
  });
};
/**
 * 图片上传公共方法
 */
util.upload = function(option, type = 'images') {
  let url = 'entry/wxapp/util.uploader.upload';
  const openid = wx.getStorageSync('userInfo').openid;
  if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
    url = util.url(url, {
      file: 'file',
      type,
    });
  }
  url += 'm=ws_party_const&';
  var option = option || {};
  switch (type) {
    case 'image':
    default:
      wx.chooseImage({
        count: option.count ? option.count : 1, // 默认1
        sizeType: option.sizeType ? option.sizeType : ['compressed'], // 可以指定是原图还是压缩图，默认压缩图
        sourceType: option.sourceType ? option.sourceType : ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success(files) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const responsePath = {};
          const tempFilePaths = files.tempFilePaths;
          responsePath.tempFilePaths = tempFilePaths;
          if (option.complete && typeof option.complete === 'function') {
            option.complete(responsePath);
          }
          wx.showLoading({
            title: '上传中...',
            mask: true,
          });
          for (const i in tempFilePaths) {
            util.uploadFile(tempFilePaths[i], i, option, tempFilePaths.length || 1);
          }
        },
      });
      break;
    case 'video':
      wx.chooseVideo({
        maxDuration: option.maxDuration ? option.maxDuration : 60, // 默认最长60s
        compressed: option.compressed != null ? option.compressed : true, // 是否压缩所选的视频源文件，默认值为true
        sourceType: option.sourceType ? option.sourceType : ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success(files) {
          // 返回选定视频的本地文件路径
          const responsePath = {};

          responsePath.tempFilePath = files.tempFilePath;

          if (option.complete && typeof option.complete === 'function') {
            option.complete(responsePath);
          }
          util.uploadFile(responsePath.tempFilePath, 0, option);
        },
      });
      break;
  }
  /**
   * 上传文件方法
   */
  util.uploadFile = function(tempFilePath, key, option, num) {
    wx.uploadFile({
      url,
      filePath: tempFilePath,
      name: 'file',
      success(result) {
        const data = JSON.parse(result.data);
        if (data.errno != 0) {
          if (option.fail && typeof option.fail === 'function') {
            option.fail(data);
          } else {
            wx.showModal({
              title: '提示',
              content: data.message,
              showCancel: false,
            });
          }
        } else {
          let responseData = {}; // 图片信息
          responseData = data;
          responseData.key = key;
          responseData.num = num;
          if (option.success && typeof option.success === 'function') {
            option.success(responseData);
          }
        }
        if (Number(num - 1) === Number(key)) {
          wx.hideLoading();
        }
      },
    }).onProgressUpdate((res) => {
      let responseProgress = {};
      responseProgress = res;
      responseProgress.key = key;
      if (option.progress && typeof option.progress === 'function') {
        option.progress(responseProgress);
      }
    });
  };

  // 判断是否JSON格式字符串
  function isJSON(str) {
    if (typeof str === 'string') {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    }
  }
};

/**
 * 转换内容中的emoji表情为 unicode 码点，在Php中使用utf8_bytes来转换输出
 */
util.parseContent = function(string) {
  if (!string) {
    return string;
  }

  const ranges = [
    '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
    '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
    '\ud83d[\ude80-\udeff]', // U+1F680 to U+1F6FF
  ];
  const emoji = string.match(
    new RegExp(ranges.join('|'), 'g'),
  );

  if (emoji) {
    for (const i in emoji) {
      string = string.replace(emoji[i], `[U+${emoji[i].codePointAt(0).toString(16).toUpperCase()}]`);
    }
  }
  return string;
};


util.date = function() {
  /**
   * 判断闰年
   * @param date Date日期对象
   * @return boolean true 或false
   */
  this.isLeapYear = function(date) {
    return (date.getYear() % 4 == 0 && ((date.getYear() % 100 != 0) || (date.getYear() % 400 == 0)));
  };

  /**
   * 日期对象转换为指定格式的字符串
   * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
   * @param date Date日期对象, 如果缺省，则为当前时间
   *
   * YYYY/yyyy/YY/yy 表示年份
   * MM/M 月份
   * W/w 星期
   * dd/DD/d/D 日期
   * hh/HH/h/H 时间
   * mm/m 分钟
   * ss/SS/s/S 秒
   * @return string 指定格式的时间字符串
   */
  this.dateToStr = function(formatStr, date) {
    formatStr = arguments[0] || 'yyyy-MM-dd HH:mm:ss';
    date = arguments[1] || new Date();
    let str = formatStr;
    const Week = ['日', '一', '二', '三', '四', '五', '六'];
    str = str.replace(/yyyy|YYYY/, date.getFullYear());
    str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : `0${date.getYear() % 100}`);
    str = str.replace(/MM/, date.getMonth() > 9 ? (date.getMonth() + 1) : `0${date.getMonth() + 1}`);
    str = str.replace(/M/g, date.getMonth());
    str = str.replace(/w|W/g, Week[date.getDay()]);
    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : `0${date.getDate()}`);
    str = str.replace(/d|D/g, date.getDate());
    str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : `0${date.getHours()}`);
    str = str.replace(/h|H/g, date.getHours());
    str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : `0${date.getMinutes()}`);
    str = str.replace(/m/g, date.getMinutes());
    str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : `0${date.getSeconds()}`);
    str = str.replace(/s|S/g, date.getSeconds());
    return str;
  };


  /**
   * 日期计算
   * @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
   * @param num int
   * @param date Date 日期对象
   * @return Date 返回日期对象
   */
  this.dateAdd = function(strInterval, num, date) {
    date = arguments[2] || new Date();
    switch (strInterval) {
      case 's':
        return new Date(date.getTime() + (1000 * num));
      case 'n':
        return new Date(date.getTime() + (60000 * num));
      case 'h':
        return new Date(date.getTime() + (3600000 * num));
      case 'd':
        return new Date(date.getTime() + (86400000 * num));
      case 'w':
        return new Date(date.getTime() + ((86400000 * 7) * num));
      case 'm':
        return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
      case 'y':
        return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
    }
  };

  /**
   * 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
   * @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
   * @param dtStart Date  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
   * @param dtEnd Date  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
   */
  this.dateDiff = function(strInterval, dtStart, dtEnd) {
    switch (strInterval) {
      case 's':
        return parseInt((dtEnd - dtStart) / 1000);
      case 'n':
        return parseInt((dtEnd - dtStart) / 60000);
      case 'h':
        return parseInt((dtEnd - dtStart) / 3600000);
      case 'd':
        return parseInt((dtEnd - dtStart) / 86400000);
      case 'w':
        return parseInt((dtEnd - dtStart) / (86400000 * 7));
      case 'm':
        return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
      case 'y':
        return dtEnd.getFullYear() - dtStart.getFullYear();
    }
  };

  /**
   * 字符串转换为日期对象 // eval 不可用
   * @param date Date 格式为yyyy-MM-dd HH:mm:ss，必须按年月日时分秒的顺序，中间分隔符不限制
   */
  this.strToDate = function(dateStr) {
    const data = dateStr;
    const reCat = /(\d{1,4})/gm;
    const t = data.match(reCat);
    t[1] -= 1;
    eval(`var d = new Date(${t.join(',')});`);
    return d;
  };

  /**
   * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
   *
   */
  this.strFormatToDate = function(formatStr, dateStr) {
    let year = 0;
    let start = -1;
    const len = dateStr.length;
    if ((start = formatStr.indexOf('yyyy')) > -1 && start < len) {
      year = dateStr.substr(start, 4);
    }
    let month = 0;
    if ((start = formatStr.indexOf('MM')) > -1 && start < len) {
      month = parseInt(dateStr.substr(start, 2)) - 1;
    }
    let day = 0;
    if ((start = formatStr.indexOf('dd')) > -1 && start < len) {
      day = parseInt(dateStr.substr(start, 2));
    }
    let hour = 0;
    if (((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len) {
      hour = parseInt(dateStr.substr(start, 2));
    }
    let minute = 0;
    if ((start = formatStr.indexOf('mm')) > -1 && start < len) {
      minute = dateStr.substr(start, 2);
    }
    let second = 0;
    if ((start = formatStr.indexOf('ss')) > -1 && start < len) {
      second = dateStr.substr(start, 2);
    }
    return new Date(year, month, day, hour, minute, second);
  };


  /**
   * 日期对象转换为毫秒数
   */
  this.dateToLong = function(date) {
    return date.getTime();
  };

  /**
   * 毫秒转换为日期对象
   * @param dateVal number 日期的毫秒数
   */
  this.longToDate = function(dateVal) {
    return new Date(dateVal);
  };

  /**
   * 判断字符串是否为日期格式
   * @param str string 字符串
   * @param formatStr string 日期格式， 如下 yyyy-MM-dd
   */
  this.isDate = function(str, formatStr) {
    if (formatStr == null) {
      formatStr = 'yyyyMMdd';
    }
    const yIndex = formatStr.indexOf('yyyy');
    if (yIndex == -1) {
      return false;
    }
    const year = str.substring(yIndex, yIndex + 4);
    const mIndex = formatStr.indexOf('MM');
    if (mIndex == -1) {
      return false;
    }
    const month = str.substring(mIndex, mIndex + 2);
    const dIndex = formatStr.indexOf('dd');
    if (dIndex == -1) {
      return false;
    }
    const day = str.substring(dIndex, dIndex + 2);
    if (!isNumber(year) || year > '2100' || year < '1900') {
      return false;
    }
    if (!isNumber(month) || month > '12' || month < '01') {
      return false;
    }
    if (day > getMaxDay(year, month) || day < '01') {
      return false;
    }
    return true;
  };

  this.getMaxDay = function(year, month) {
    if (month == 4 || month == 6 || month == 9 || month == 11) return '30';
    if (month == 2) {
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) return '29';
      return '28';
    }
    return '31';
  };
  /**
   *	变量是否为数字
   */
  this.isNumber = function(str) {
    const regExp = /^\d+$/g;
    return regExp.test(str);
  };

  /**
   * 把日期分割成数组 [年、月、日、时、分、秒]
   */
  this.toArray = function(myDate) {
    myDate = arguments[0] || new Date();
    const myArray = Array();
    myArray[0] = myDate.getFullYear();
    myArray[1] = myDate.getMonth();
    myArray[2] = myDate.getDate();
    myArray[3] = myDate.getHours();
    myArray[4] = myDate.getMinutes();
    myArray[5] = myDate.getSeconds();
    return myArray;
  };

  /**
   * 取得日期数据信息
   * 参数 interval 表示数据类型
   * y 年 M月 d日 w星期 ww周 h时 n分 s秒
   */
  this.datePart = function(interval, myDate) {
    myDate = arguments[1] || new Date();
    let partStr = '';
    const Week = ['日', '一', '二', '三', '四', '五', '六'];
    switch (interval) {
      case 'y':
        partStr = myDate.getFullYear();
        break;
      case 'M':
        partStr = myDate.getMonth() + 1;
        break;
      case 'd':
        partStr = myDate.getDate();
        break;
      case 'w':
        partStr = Week[myDate.getDay()];
        break;
      case 'ww':
        partStr = myDate.WeekNumOfYear();
        break;
      case 'h':
        partStr = myDate.getHours();
        break;
      case 'm':
        partStr = myDate.getMinutes();
        break;
      case 's':
        partStr = myDate.getSeconds();
        break;
    }
    return partStr;
  };

  /**
   * 取得当前日期所在月的最大天数
   */
  this.maxDayOfDate = function(date) {
    date = arguments[0] || new Date();
    date.setDate(1);
    date.setMonth(date.getMonth() + 1);
    const time = date.getTime() - 24 * 60 * 60 * 1000;
    const newDate = new Date(time);
    return newDate.getDate();
  };
};

util.getImgUrl = function() {
  const app = getApp();
  return app.siteInfo.domain + 'addons/ws_party_const/static/images/app/localicon/';
};

module.exports = util;